// 回调函数串行
export type CallBackFinished = (finished: () => void) => void

export class CallBackSerialUtils {
  private count = 0;
  private readonly max: number = 0
  private list: CallBackFinished[] = []

  constructor(max = 1) {
    this.max = max
  }

  private createTask(call: CallBackFinished) {
    return () => {
      this.count++
      setTimeout(() => {
        call(() => {
          this.count--
          if (this.list.length) {
            const task = this.list.shift()
            // @ts-ignore
            task()
          }
        })
      }, 0)
    }
  }

  call(call: CallBackFinished) {
    const task = this.createTask(call)
    if (this.count >= this.max) {
      this.list.push(task)
    } else {
      task()
    }
  }
}



























